#pragma once

#include <iostream>
#include <sys/epoll.h>
#include "Log.hpp"
#include "Common.hpp"

using namespace LogModule;

namespace EpollModule
{
    class Epoller
    {
    public:
        Epoller()
            : _epfd(-1)
        {
        }

        void Init()
        {
            _epfd = ::epoll_create(256);
            if (_epfd == -1)
            {
                LOG(LogLevel::ERROR) << "epoll_create error..." << _epfd;
                exit(EPOLL_CREATE_ERR);
            }
            LOG(LogLevel::ERROR) << "epoll_create create success , _epfd: " << _epfd;
        }

        int Wait(struct epoll_event revs[], int num) // 输出就绪的fd和num
        {
            int n = epoll_wait(_epfd, revs, num, -1);
            if (n < 0)
            {
                LOG(LogLevel::WARNING) << "epoll_wait error";
            }
            LOG(LogLevel::ERROR) << "epoll_wait create success , _epfd: " << _epfd;

            return n;
        }

        void Ctrl(int sockfd, uint16_t events)
        {
            struct epoll_event ev;
            ev.events = EPOLLIN;
            ev.data.fd = sockfd;
            LOG(LogLevel::WARNING) << "sockfd : "<< sockfd;
            
            int n = ::epoll_ctl(_epfd, EPOLL_CTL_ADD, sockfd, &ev);
            if (n < 0)
            {
                LOG(LogLevel::WARNING) << "epoll_ctl error";
            }
        }
        ~Epoller()
        {
        }

    private:
        int _epfd;
    };
}